/**
 * 
 */
package slhs.tempo.scriptGenerator;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

/**
 * ExcelSegmentsImporter2.java
 * 
 * @author Swapnil Devikar
 * 
 */
public class ExcelSegmentsImporter implements ExcelImporter {
    private static final String SEGMENT_START_TOKEN_CAPS = "Segment";
    private static final String SEGMENT_START_TOKEN_SMALL = "segment";
    private static final String DEFAULT_DELIMITER = ";";
    private static final String NO_DELIMITER = "";
    private List<String> scriptLines = new ArrayList<String>();

    /*
     * (non-Javadoc)
     * 
     * @see slhs.tempo.scriptGenerator.ExcelImporter#importFile(java.lang.String)
     */
    @Override
    public List<String> importFile(String fileName) {

	addSegmentTimings(fileName, UtilityConstants.SEGMENT_TIMING_START_TOKEN,
		UtilityConstants.SEGMENT_TIMING_END_TOKEN);
	addSegmentTimings(fileName, UtilityConstants.SEGMENT_CONFIGURATION_START_TOKEN,
		UtilityConstants.SEGMENT_CONFIGURATION_END_TOKEN);

	return scriptLines;
    }

    /**
     * 
     */
    private void addSegmentData(String fileName) {
	// TODO Auto-generated method stub

    }

    /**
     * 
     */
    private void addSegmentTimings(String fileName, String startToken, String endToken) {
	ExcelExtractor data = new ExcelExtractor(fileName);
	data.open();
	Iterator<Row> rowIterator = data.getRowIterator();
	boolean dataStartFlag = false;
	// skip until passed token
	skipUntilToken(startToken, rowIterator);

	while (rowIterator.hasNext()) {
	    // Iterate over each cell in each row and try to figure out what they mean
	    String currentCellValue = "";
	    Row currentRow = rowIterator.next();
	    for (Cell cellValue : currentRow) {
		currentCellValue = getCellValueAsString(cellValue);
		// End reading if the end token encountered
		if (currentCellValue.equals(endToken)) {
		    break;
		} // record cell as a comment to appear preceded by %
		else if (currentCellValue.startsWith(SEGMENT_START_TOKEN_CAPS)
			|| currentCellValue.startsWith(SEGMENT_START_TOKEN_SMALL)) {
		    printAsInformativeString(currentCellValue);
		    dataStartFlag = true;

		} // record cell as delimited value
		else if ((currentRow.getLastCellNum() > 0)) {
		    // means either delimited values or table column headers
		    if (dataStartFlag && !currentCellValue.equals("") && (currentCellValue != null)) {
			if (isLastNonEmptyColumn(currentRow, cellValue)) {
			    // if last in the row, don't attach ;
			    // System.out.println("-->current cell value" + currentCellValue);
			    printAsDelimitedValue(currentCellValue, NO_DELIMITER, "\n");
			    dataStartFlag = false;
			}

			else {
			    // if not last in the row, attach ;
			    // System.out.println("-->current cell value" + currentCellValue);

			    printAsDelimitedValue(currentCellValue, DEFAULT_DELIMITER, "");
			}
			/* reset flag */
		    }

		} // if any of the above criteria don't match, it much be a comment
		else {
		    printAsComment(getCellValueAsString(cellValue));

		}
	    }
	    if (currentCellValue.equals(endToken)) {
		break;
	    }
	}

    }

    /**
     * @param currentRow
     * @param cellValue
     * @return
     */
    private boolean isLastNonEmptyColumn(Row currentRow, Cell cellValue) {
	boolean retVal = false;
	int nonBlankValueColumnIndex = 0;
	int columnIndex = cellValue.getColumnIndex();
	for (Cell currentCell : currentRow) {
	    String value = getCellValueAsString(currentCell);
	    if (!value.equals("") && (value != null)) {
		nonBlankValueColumnIndex = currentCell.getColumnIndex();
	    }
	}
	retVal = (columnIndex == nonBlankValueColumnIndex);
	return retVal;
    }

    /**
     * @param cellValue
     */
    private void printAsComment(String cellValue) {
	scriptLines.add("#\n");
	System.out.println("#");

	scriptLines.add(cellValue + "\n");
	System.out.println(cellValue);

	scriptLines.add("#\n");
	System.out.println("#");

    }

    /**
     * @param currentCellValue
     * @param noDelimiter
     */
    private void printAsDelimitedValue(String currentCellValue, String delimiter, String optionalNewLine) {
	scriptLines.add(currentCellValue + delimiter + optionalNewLine);
	System.out.print(currentCellValue + delimiter + optionalNewLine);

    }

    /**
     * 
     */
    private void printAsInformativeString(String currentCellValue) {
	scriptLines.add("%\n");
	System.out.println("%");

	scriptLines.add("%" + currentCellValue + "\n");
	System.out.println("%" + currentCellValue);

	scriptLines.add("%\n");
	System.out.println("%");

    }

    /**
     * @param cellValue
     * @return
     */
    private String getCellValueAsString(Cell cellValue) {
	if (cellValue == null) {
	    return "";
	}
	switch (cellValue.getCellType()) {
	case Cell.CELL_TYPE_STRING:
	    return cellValue.getRichStringCellValue().toString();
	case Cell.CELL_TYPE_NUMERIC:
	    return Integer.toString((int) cellValue.getNumericCellValue());
	default:
	    return "";

	}
    }

    /**
     * @param token
     * @param iterator
     */
    private void skipUntilToken(String token, Iterator<Row> iterator) {
	boolean foundToken = false;
	while (iterator.hasNext()) {
	    Row currentRow = iterator.next();
	    // Skip till you reach the passed token
	    for (Cell currentCellValue : currentRow) {
		String value = currentCellValue.toString();
		if (value.equals(token)) {
		    foundToken = true;
		    break;
		}
	    }
	    if (foundToken)
		break;
	}
    }
}
